package com.woniu.controller;

import cn.dev33.satoken.util.SaResult;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.woniu.entity.*;
import com.woniu.service.CtfRangeService;
import com.woniu.service.CtfScoreDifficultyService;
import com.woniu.util.ResponseData;
import com.woniu.utils.ResponseMyEntity;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.codec.multipart.FilePart;
import org.springframework.http.codec.multipart.Part;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;
import com.woniu.mapper.CtfRangeMapper;
import reactor.core.publisher.Mono;


import java.util.List;

/**
 * @Author hq
 * @Date 2025/6/10$ 10:24$
 * 镜像表表控制器
 * @Author pml hq
 * @Date 2025/6/9 17:56
 * @Description TODO
 **/
@Slf4j
@RestController
@RequestMapping("/range")
public class CtfRangeController {
    @Autowired
    private CtfRangeMapper ctfRangeMapper;
    @Autowired
    private CtfRangeService rangeService;
    @Autowired
    private CtfScoreDifficultyService ctfScoreDifficultyService;

    /**
     * @author  hq
     * @Description  上传镜像文件
     * @param targetRangeFile 镜像文件
     * @param targetRangeName 输入镜像名称
     * @param targetRangeType 输入镜像类型
     * @param difficultyIdStr 输入镜像难度
     * @param description 输入镜像描述
     * @return
     */
    // 修改原方法，统一参数类型为 @RequestPart
    @PostMapping(value = "/uploadTargetRange", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public Mono<ResponseMyEntity> uploadRange(
            @RequestPart("targetRangeFile") FilePart targetRangeFile,
            @RequestPart("targetRangeName") String targetRangeName,
            @RequestPart("targetRangeType") String targetRangeType,
            @RequestPart("difficultyId") String difficultyIdStr,
            @RequestPart("flagPath") String flagPath,
            @RequestPart("description") String description,
            @RequestPart("exposePort") String exposePort) {
        try {
            Integer difficultyId = Integer.valueOf(difficultyIdStr);
            return Mono.fromCallable(() -> {
                rangeService.insertRange(targetRangeFile, targetRangeName,
                        targetRangeType, difficultyId,flagPath, description, exposePort);
                return ResponseMyEntity.SUCCESS;
            });
        } catch (Exception e) {
            return Mono.just(ResponseMyEntity.ERROR);
        }
    }
    //添加镜像
    @PostMapping("/add")
    public ResponseMyEntity add(@RequestBody CtfRange range) {
        rangeService.addRange(range);
        return ResponseMyEntity.SUCCESS;
    }
    /**
     * @author  hq
     * @param rangeId
     * @param
     * @return
     */
    @DeleteMapping("/deleteTargetRange/{rangeId}")
    public ResponseMyEntity deleteRange(@PathVariable String rangeId) {
        rangeService.deleteRange(rangeId, true);
        return ResponseMyEntity.SUCCESS;
    }


    @PostMapping("delete")
    public SaResult deleteRangeNew(@RequestBody CtfRange range){
        rangeService.deleteRange(range.getRangeId(), true);
        return new SaResult().setCode(200);
    }
    /**
     * @Description 修改
     * @Param
     * @Return
     * @Author pml
     * @Date 2025/6/11 16:12
     */
    @PutMapping("/update")
    public SaResult update(@RequestBody CtfRange range) {
        log.info("修改数据："+range);
//        return SaResult.ok().setData(ctfRangeMapper.updateById(range));
        // 修改：通过Service调用更新方法
        rangeService.updateByRangeId(range);
        return SaResult.ok();
    }
    /**
     * @Description 根据字符串id查
     * @Param
     * @Return
     * @Author pml
     * @Date 2025/6/11 16:12
     */
    @GetMapping("/get/{id}")
    public SaResult getById(@PathVariable String id) {
//        return SaResult.ok().setData(ctfRangeMapper.selectById(id));
        // 修改：通过Service调用查询方法
        return SaResult.ok().setData(rangeService.getById(id));
    }


    /**
     * * @Author hq
     *      * 分页查询
     *      * @return TableDataInfo
     * @Description 查询所有
     * @Param
     * @Return
     * @Author pml
     * @Date 2025/6/11 16:12
     */
    @GetMapping("/list")
    public SaResult list() {
        List<CtfRange> list = rangeService.selectPage();
        return SaResult.ok().setData(list);
//        return SaResult.ok().setData(ctfRangeMapper.selectList(null));
        // 修改：通过Service调用查询所有方法
//        return SaResult.ok().setData(rangeService.list());
    }

    @GetMapping("/list2")
    public SaResult list2() {
//        List<CtfRange> list = rangeService.selectPage();
//        return SaResult.ok().setData(list);
//        return SaResult.ok().setData(ctfRangeMapper.selectList(null));
        // 修改：通过Service调用查询所有方法
        return SaResult.ok().setData(rangeService.list());
    }

    /**
     * @Description 多条件查
     * @Param
     * @Return
     * @Author pml
     * @Date 2025/6/11 16:12
     */
    @GetMapping("/search")
    public SaResult search(@RequestParam String keyword) {
//        QueryWrapper<CtfRange> wrapper = new QueryWrapper<>();
//        wrapper.like("range_name", keyword)    // 靶场名称
//                .or().like("range_desc", keyword)  // 靶场描述
//                .or().like("updater", keyword)    // 新增：更新人（如用户ID或用户名）
//                .or().like("uploader", keyword);  // 新增：上传人
//        return SaResult.ok().setData(ctfRangeMapper.selectList(wrapper));
        // 修改：通过Service调用搜索方法，将查询逻辑移至Service层
        return SaResult.ok().setData(rangeService.searchRanges(keyword));
    }

    /**
     * @Author zhaoj
     * @Date 2025/6/11 19:19
     * @Description 获取当前考试靶场信息
     * @Params
     * @Return
     **/
    @PostMapping("queryRange")
    public SaResult queryRange(@RequestBody CtfContest contest){
        MPJLambdaWrapper<CtfRange> wrapper = new MPJLambdaWrapper<>();
        wrapper.leftJoin(RelContestRange.class,RelContestRange::getRangeId,CtfRange::getRangeId)
                .eq(RelContestRange::getContestId,contest.getContestId())
                .selectAll(CtfRange.class);
        List<CtfRange> list = ctfRangeMapper.selectJoinList(CtfRange.class,wrapper);
        return new SaResult().setData(list);
    }
    /**
     * @return TableDataInfo
     * @Author hq
     * 分页查询
     */
    @GetMapping("/listPage")
    public SaResult listPage(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            CtfRange range) {
        PageBean<CtfRange> pageInfo =rangeService.selectPage(pageNum,pageSize,range);
        return SaResult.ok().setData(pageInfo);
    }

//    根据id查询题目困难度
@GetMapping("/getdifficulty")
public SaResult getDifficultyById(@RequestParam("difficultyId") Integer difficultyId) {
    CtfScoreDifficulty difficulty = ctfScoreDifficultyService.getById(difficultyId);
    return SaResult.ok().setData(difficulty);
}
//查询困难表
    @GetMapping("/getdifficultylist")
    public SaResult getDifficultyList() {
        List<CtfScoreDifficulty> list = ctfScoreDifficultyService.list();
        return SaResult.ok().setData(list);
    }
//    根据rangId上传镜像
@PostMapping(value = "/uploadImageByRangeId", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public Mono<SaResult> uploadImageByRangeId(
        @RequestPart("rangeId") String rangeId,
        @RequestPart("file") FilePart file) {
    return rangeService.uploadImageByRangeId(rangeId, file)
            .map(url -> SaResult.ok().setData(url));
}
}